package com.dapeis.api.controller.collocation.impl;

import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import com.ag.core.base.Pager;
import com.ag.utils.DictionarySettingUtils;
import com.ag.utils.NumberUtils;
import com.ag.utils.json.AGsonBuilder;
import com.dapeis.api.controller.RestController;
import com.dapeis.api.controller.collocation.IGarderobeController;
import com.dapeis.core.utils.DBConfigUtils;
import com.dapeis.core.utils.StylistConfig;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.domain.Garderobe;
import com.dapeis.domain.ext.GarderobeExt;
import com.dapeis.exception.StateDisableException;
import com.dapeis.im.tim.TIMUtil;
import com.dapeis.service.COSFileService;
import com.dapeis.service.GarderobeService;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

/**
 * 
 * @author win7
 * 
 */
@Controller
@RequestMapping("/dps/garderobe")
public class GarderobeControllerImpl extends RestController
		implements IGarderobeController {
	@Resource
    COSFileService cosFileService;
	@Resource
	GarderobeService garderobeService;

	@Override
	public JsonElement add(@RequestParam(required = false) String name,@RequestParam(required = false) String remark,
			 String typeCode,MultipartFile img, HttpServletRequest request) {
		if (StringUtils.isNotBlank(typeCode) && null != img
				&& checkParamSetting(typeCode)) {
			 String imgPath = cosFileService.saveFile(img,
					    StylistConstants.UploadType.GARDEROBE, request);
			 if (null != imgPath) {
				Garderobe garderobe = new Garderobe();
				garderobe.setImgUrl(imgPath);
				garderobe.setCreateTime(new Date().getTime() / 1000);
				if(name != null){
					garderobe.setName(name);
				}
				if(remark!= null){
					garderobe.setRemark(remark);
				}
				garderobe.setTypeCode(typeCode);
				garderobe.setType(StylistConstants.GarderobeType.DPS);
				garderobe.setUserId(getThreadLocalCollocationId());
				garderobeService.insert(garderobe);
				JsonObject json = buildSuccess();
				json.add("garderobe",
					AGsonBuilder.create().toJsonTree(garderobe));
				json.addProperty("typeCode", typeCode);
				json.addProperty("typeName", getParamValue(typeCode));
				return json;
			 }
			 throw new InvalidParameterException("图库添加失败");
		}
		throw new InvalidParameterException("衣橱类型匹配失败");
	}

	@Override
	public JsonElement delete(Long gid, HttpServletRequest request) {
		Garderobe garderobe = garderobeService.selectByPrimaryKey(gid);
		if (null != garderobe) {
		    if (garderobe.getState().equals(StylistConstants.State.DISABLE)) {
			throw new StateDisableException();
		    }
		    garderobe.setState(StylistConstants.State.DISABLE);
		    garderobeService.updateByPrimaryKeySelective(garderobe);
		    JsonObject json = buildSuccess();
		    return json;
		}
		throw new InvalidParameterException("查询不到衣橱信息ID:" + gid);
	    
	}

	@Override
	public JsonElement list(@RequestParam String typeCode , @RequestParam(required = false) Integer p,HttpServletRequest request) {
			Pager pager = new Pager();
			// 查询所有
			//pager.setPageSize(10000);
			Example example = new Example(Garderobe.class);
			Criteria criteria = example.createCriteria();
			criteria.andEqualTo(Garderobe.PROPERTY_TYPE,StylistConstants.GarderobeType.DPS);
			criteria.andEqualTo(Garderobe.PROPERTY_USERID,getThreadLocalCollocationId());
			System.out.println(getThreadLocalCollocationId());
			criteria.andEqualTo(Garderobe.PROPERTY_STATE, StylistConstants.State.NORMAL);
			criteria.andEqualTo(Garderobe.PROPERTY_TYPECODE, typeCode);
			pager.setExample(example);
			if(NumberUtils.isValid(p)){
				pager.setCurrentPage(p);
			}
			garderobeService.pager(pager);
			List<Garderobe> list = pager.getItemList();
			// 获取所有分类列表
			Map<String, String> typeMap = DictionarySettingUtils
				.getParameterMap(StylistConfig.GARDEOROBE_DPS_CONFIG);

			List<GarderobeExt> resultList = new ArrayList<GarderobeExt>();
			for (String k : typeMap.keySet()) {
			    List<Garderobe> temp = new ArrayList<Garderobe>();
			    for (Garderobe ga : list) {
				if (ga.getTypeCode().equals(k)) {
				    temp.add(ga);
				}
			    }
			    if (!temp.isEmpty()) {
				GarderobeExt garderobeExt = new GarderobeExt();
				garderobeExt.setGarderobes(temp);
				garderobeExt.setTypeCode(k);
				garderobeExt.setTypeName(getParamValue(k));
				resultList.add(garderobeExt);
			    }
			}
			JsonObject resultJsonObject = buildSuccess();
			JsonArray jsonArray = new JsonArray();
			for (GarderobeExt ext : resultList) {
			    JsonObject json = new JsonObject();
			    json.addProperty("typeCode", ext.getTypeCode());
			    json.addProperty("typeName", ext.getTypeName());
			    json.add("list",
				    AGsonBuilder.create().toJsonTree(ext.getGarderobes()));
			    jsonArray.add(json);
			}
			resultJsonObject.add("list", jsonArray);
			//return AGsonBuilder.create().toJsonTree(pager);
			return resultJsonObject;
	}

	@Override
	public JsonElement detail(Long gid, HttpServletRequest request) {
		Garderobe garderobe = garderobeService.selectByPrimaryKey(gid);
		if (null != garderobe) {
		    if (garderobe.getState().equals(StylistConstants.State.DISABLE)) {
			throw new StateDisableException();
		    }
		    JsonObject json = buildSuccess();
		    json.addProperty("typeCode", garderobe.getTypeCode());
		    json.addProperty("typeName", getParamValue(garderobe.getTypeCode()));
		    // 此处因前端要求，独立到外层
		    json.addProperty("id", garderobe.getId());
		    json.addProperty("name", garderobe.getName());
		    json.addProperty("remark", garderobe.getRemark());
		    json.addProperty("imgUrl",DBConfigUtils.getFullImgPath(garderobe.getImgUrl()));

		    return json;
		}
		throw new InvalidParameterException("查询不到衣橱信息ID:" + gid);
	}

	@Override
	public JsonElement modify(Long gid, String name, String remark,
			String typeCode, MultipartFile img, HttpServletRequest request) {
		Garderobe garderobe = garderobeService.selectByPrimaryKey(gid);
		if (null != garderobe) {
		    garderobe.setName(name);
		    garderobe.setRemark(remark);
		    garderobe.setTypeCode(typeCode);
		    if (null != img && img.getSize() > 10) {
			String filePath = cosFileService.saveFile(img,
				StylistConstants.UploadType.GARDEROBE, request);
			if (null != filePath) {
			    garderobe.setImgUrl(filePath);
			}
		    }
		    garderobeService.updateByPrimaryKeySelective(garderobe);
		    JsonObject json = buildSuccess();
		    return json;
		}
		throw new InvalidParameterException("查询不到衣橱信息ID:" + gid);
	}

	 /**
     * 检查前端传回来的参数是否已经配置
     * @return
     */
    public boolean checkParamSetting(String typeCode) {
	Map<String, String> typeMap = DictionarySettingUtils
		.getParameterMap(StylistConfig.GARDEOROBE_DPS_CONFIG);
	boolean isContain = typeMap.containsKey(typeCode);
	if (!isContain) {
	    return false;
	}
	return true;
    }
    
    public String getParamValue(String typeCode) {
    	return DictionarySettingUtils
    		.getParameterValue(StylistConfig.GARDEOROBE_DPS_CONFIG + "."
    			+ typeCode);
    }
    
    public String getUserParamValue(String typeCode) {
    	return DictionarySettingUtils
    		.getParameterValue(StylistConfig.GARDEOROBE_CONFIG + "."
    			+ typeCode);
    }

    /**
     * 客户衣橱列表
     */
	@Override
	public JsonElement customerList(String userTimId, @RequestParam(required = false) Integer p, HttpServletRequest request) {
		Integer userId = TIMUtil.getWXId(userTimId);
		Pager pager = new Pager();
		// 查询所有
		//pager.setPageSize(10000);
		Example example = new Example(Garderobe.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo(Garderobe.PROPERTY_TYPE,StylistConstants.GarderobeType.USER);
		criteria.andEqualTo(Garderobe.PROPERTY_USERID,userId);
		criteria.andEqualTo(Garderobe.PROPERTY_STATE, StylistConstants.State.NORMAL);
		pager.setExample(example);
		if(NumberUtils.isValid(p)){
			pager.setCurrentPage(p);
		}
		garderobeService.pager(pager);
		List<Garderobe> list = pager.getItemList();
		// 获取所有分类列表
		Map<String, String> typeMap = DictionarySettingUtils
			.getParameterMap(StylistConfig.GARDEOROBE_CONFIG);

		List<GarderobeExt> resultList = new ArrayList<GarderobeExt>();
		for (String k : typeMap.keySet()) {
		    List<Garderobe> temp = new ArrayList<Garderobe>();
		    for (Garderobe ga : list) {
			if (ga.getTypeCode().equals(k)) {
			    temp.add(ga);
			}
		    }
		    if (!temp.isEmpty()) {
			GarderobeExt garderobeExt = new GarderobeExt();
			garderobeExt.setGarderobes(temp);
			garderobeExt.setTypeCode(k);
			garderobeExt.setTypeName(getUserParamValue(k));
			resultList.add(garderobeExt);
		    }
		}
		JsonObject resultJsonObject = buildSuccess();
		JsonArray jsonArray = new JsonArray();
		for (GarderobeExt ext : resultList) {
		    JsonObject json = new JsonObject();
		    json.addProperty("typeCode", ext.getTypeCode());
		    json.addProperty("typeName", ext.getTypeName());
		    json.add("list",
			    AGsonBuilder.create().toJsonTree(ext.getGarderobes()));
		    jsonArray.add(json);
		}
		resultJsonObject.add("list", jsonArray);
		//return AGsonBuilder.create().toJsonTree(pager);
		return resultJsonObject;
	}
}
